//
//  FindUpdataViewController.m
//  AriseSamePro
//
//  Created by 包日守 on 15/10/22.
//  Copyright © 2015年 Arise. All rights reserved.
//

#import "FindUpdataViewController.h"
#import "ARGlobalInterface.h"
#import "ARChannelModel.h"
#import "AFNetworking.h"
#import "ChannelCell.h"

#define TABBAR_HEIGHT 49
#define NAVAGATEBAR_HEIGHT 44
#define STARBAR_HEIGHT 20

@interface FindUpdataViewController ()

//
@end

@implementation FindUpdataViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self.tableView registerNib:[UINib nibWithNibName:@"ChannelCell" bundle:nil] forCellReuseIdentifier:@"ChannelCellID"];
    
    self.tableView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - TABBAR_HEIGHT - NAVAGATEBAR_HEIGHT - STARBAR_HEIGHT);
    
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:[ARGlobalInterface findLastCacheURL]]) {
        [self loadDataInCache];
        
    }
    else
        
    {
        [self loadDataInServer];
        
    }

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - superMethe


- (void) loadDataInCache
{
    [super loadDataInCache];
    NSData *data = [NSData dataWithContentsOfFile:[ARGlobalInterface findLastCacheURL]];
    
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    
    self.nextURL = dict[@"data"][@"next"];
    NSArray *array = dict[@"data"][@"results"];
    NSMutableArray *marray = [NSMutableArray array];
    for (NSDictionary *dicts in array) {
        ARChannelModel *model = [[ARChannelModel alloc] init];
        [model setValuesForKeysWithDictionary:dicts];
        [marray addObject:model];
    }
    
    self.dataArray = marray;
    

    
}
- (void) loadDataInServer
{
    [super loadDataInServer];
    
    NSString *serverURL = [ARGlobalInterface findLastServerURL];
    NSString *cacheURL = [ARGlobalInterface findLastCacheURL];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager GET:serverURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSData *data = responseObject;
        
        [data writeToFile:cacheURL atomically:YES];
        
        
        
        //initialized 为总完成下载数量  全部下载线程完成后 执行
        if (++ self.initialized == 1) {
            [self loadDataInCache];
            [self loadDataInServerComplete];
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
    
    
}



- (void)loadDataMore
{
    [super loadDataMore];
    
    
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager GET:[ARGlobalInterface findMoreServerURLWithID:self.nextURL] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSMutableArray *marray = [NSMutableArray arrayWithArray:self.dataArray];
        
        
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
        self.nextURL = dict[@"data"][@"next"];
        NSArray *array = dict[@"data"][@"results"];
        
        for (NSDictionary *dicts in array) {
            ARChannelModel *model = [[ARChannelModel alloc] init];
            [model setValuesForKeysWithDictionary:dicts];
            [marray addObject:model];
        }
        
        self.dataArray = marray;
        
        [self loadDataInServerComplete];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
    
}


#pragma mark - tableViewDelegate


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return self.dataArray.count;
    
    
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    ARChannelModel *channel = self.dataArray[indexPath.row];
    
    ChannelCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ChannelCellID"];
    
    cell.channel = channel;
    
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
    
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    ARChannelModel *channel = self.dataArray[indexPath.row];
    
    if (self.delegate) {
        [self.delegate findUpdataViewController:self WithChannel:channel];
    }

}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
